package com.cn.jinl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.jinl.conf.Config;
import com.cn.jinl.domain.ChanjetReturn;
import com.cn.jinl.domain.EncryptMsg;
import com.cn.jinl.utils.msgSend.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created On : 2024/2/22.
 * <p>
 * Author : Huiyan
 * <p>
 * Description: ChanjetTestController
 */
@Controller
@RequestMapping("/chanjet")
public class ChanjetTestController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Config config;

    @ResponseBody
    @RequestMapping("/api/testChanjet")
    public ChanjetReturn testChanjet(@RequestBody EncryptMsg encryptMsg) throws Exception {
        System.out.println("--------testChanjet------------");
        ChanjetReturn response = new ChanjetReturn();
        response.setResult("success");
        Object tokenJson = redisTemplate.opsForValue().get("tokenKey");
        if(null != tokenJson){
            return response;
        }
        System.out.println("--------------------");
        String msg = encryptMsg.getEncryptMsg();
        String key = "1234567812345678";
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
        byte[] bytes = new BASE64Decoder().decodeBuffer(msg);
        bytes = cipher.doFinal(bytes);
        String result = new String(bytes,StandardCharsets.UTF_8);
        JSONObject ticketJson = JSON.parseObject(result);
        if(null == ticketJson){
            return response;
        }
        JSONObject bizContent = ticketJson.getJSONObject("bizContent");
        if(null == bizContent){
            return response;
        }
        String ticket = bizContent.getString("appTicket");
        if(StringUtils.isEmpty(ticket)){
            return response;
        }
        String url = "https://openapi.chanjet.com/v1/common/auth/selfBuiltApp/generateToken";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appTicket", ticket);
        jsonObject.put("certificate", config.certificate);

        String body = jsonObject.toJSONString();
        JSONObject header = new JSONObject();
        header.put("appKey",config.appKey);
        header.put("appSecret",config.appSecret);
        result = HttpClientUtil.postJsonWithHeader(url, body, null,header);
        if(StringUtils.isEmpty(result)){
            return response;
        }
        JSONObject accessToken = JSONObject.parseObject(result);
        JSONObject value = accessToken.getJSONObject("value");
        if(null == value){
            return response;
        }
        String token = value.getString("accessToken");
        int expiresIn = 3600;
        if(null != value.get("expiresIn")){
            expiresIn = value.getIntValue("expiresIn");
        }
        //提前一小时过期
        long actualExpireTime = (expiresIn - 3600L) > 0?(expiresIn - 3600L):expiresIn;

        redisTemplate.opsForValue().set("tokenKey",token,actualExpireTime, TimeUnit.SECONDS);
        return response;
    }
}
